package com.hxh.component.business.ui.face.main;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.hxh.component.basicore.component.mvp.persenter.BasePresenter;
import com.hxh.component.basicore.component.net.IApiError;
import com.hxh.component.basicore.util.Utils;
import com.hxh.component.basicore.util.rx.normalhttpstyle.NormalSubscribe;
import com.hxh.component.business.app.App;
import com.hxh.component.business.common.api.ApiFactory;
import com.hxh.component.business.ui.bean.faceCheckBean;
import com.hxh.component.business.utils.oss.api.OSSUtil;
import com.hxh.component.business.utils.oss.bean.OssUpLoadResultBean;

import java.util.HashMap;

import rx.Observable;
import rx.functions.Func1;

import static com.hxh.component.business.utils.Constant.SpTag.IDENTITY_CARD_ID;
import static com.hxh.component.business.utils.Constant.SpTag.IDENTITY_CARD_NAME;

/**
 * 创建者：hxh
 * 时间：  2017/9/6
 * 描述：
 */
public class LoadingActivityPersenter extends BasePresenter<LoadingActivity> implements LoadingActivityContract.P {


    @Override
    public void uploadFaceImg(final HashMap<String, String> values, final String delta) {
        //getView().showFaceChecerResult(true);

        final String name = Utils.SP.getString(IDENTITY_CARD_NAME);
        final String identity_card_id = Utils.SP.getString(IDENTITY_CARD_ID);
        addSubscription(
                Observable
                        .just(values)
                        .map(new Func1<HashMap<String, String>, String>() {
                            @Override
                            public String call(HashMap<String, String> val) {
                                StringBuffer imagesbody = new StringBuffer("\"images\":{");

                                String imgjson = null;

                                int size = val.keySet().size();
                                String[] mKeys = new String[size];
                                val.keySet().toArray(mKeys);


                                for (int i = 0; i < size; i++) {

                                    OssUpLoadResultBean ossUpLoadResultBeen = JSON.parseObject(val.get(mKeys[i]), OssUpLoadResultBean.class);

                                    if (i < size - 1) {
                                        imgjson = "\"" + mKeys[i] + "\":" + "\"" + "/" + ossUpLoadResultBeen.getBucket() + "/" + ossUpLoadResultBeen.getObject() + "\",";
                                    } else {
                                        imgjson = "\"" + mKeys[i] + "\":" + "\"" + "/" + ossUpLoadResultBeen.getBucket() + "/" + ossUpLoadResultBeen.getObject() + "\"";
                                    }
                                    imagesbody.append(imgjson);
                                }
                                imagesbody.append("}");
                                return imagesbody.toString();
                            }
                        })
                        .map(new Func1<String, String>() {
                            @Override
                            public String call(String s) {
                                StringBuffer sb = new StringBuffer("{\n");
                                sb.append("\"face_image_type\":");
                                sb.append("\"meglive\"");
                                sb.append(",");
                                sb.append("\"id_card_name\":");
                                sb.append("\"" + name + "\"");
                                sb.append(",");
                                sb.append("\"id_card_number\":");
                                sb.append("\"" + identity_card_id + "\"");
                                sb.append(",");
                                sb.append("\"delta\":");
                                sb.append("\"" + delta + "\"");
                                sb.append(",");
                                sb.append(s);
                                sb.append("}");
                                return sb.toString();
                            }
                        })

                        .flatMap(new Func1<String, Observable<String>>() {
                            @Override
                            public Observable<String> call(String body) {
                                return ApiFactory.verityFace(body);
                            }
                        })

                        .subscribe(new NormalSubscribe<String>(true) {
                            @Override
                            public void _OnError(Throwable msg) {
                                IApiError error = getApiError(msg);
                                if (null != error) {
                                    if (error.getErrorCode() == 400) {
                                        getView().showFaceChecerResult(false, "图片模糊或非本人操作，请重试");

                                    } else
                                        getView().showFaceChecerResult(false, error.getErrorMessage());
                                } else getView().showFaceChecerResult(false, "未知错误，请再次尝试");

                                //getView().showFaceChecerResult(false,getApiError(msg).getErrorMessage());

                            }

                            @Override
//                            public void _OnNet(faceCheckBean bean) {
                            public void _OnNet(String bean) {
                                faceCheckBean faceCheckBean = JSON.parseObject(bean, faceCheckBean.class);
                                if (faceCheckBean.getResult_faceid().getConfidence() > faceCheckBean.getResult_faceid().getThresholds().get_1e3())
                                    getView().showFaceChecerResult(true, null);
                                else
                                    getView().showFaceChecerResult(false, "图片模糊或非本人操作，请重试");
                            }
                        })

        );

    }


    private OssUpLoadResultBean uploadFile(byte[] path) {
        try {
            PutObjectResult result = OSSUtil.putObject(getView(), OSSUtil.mDefaultinitOSSResponse, path, App.getAppInitDelegate().getAppCacheDir() + Utils.FileUtil.generatePictureName() + ".jpeg");
            String resultData = new String(result.getServerCallbackReturnBody().getBytes(), "utf-8");

            return JSON.parseObject(resultData, OssUpLoadResultBean.class);
        } catch (Exception e) {

        }
        return null;
    }
}
